package com.tiger.project.service.impl;

import com.tiger.project.domain.AssetMonth;
import com.tiger.project.mapper.AssetMapper;
import com.tiger.project.mapper.AssetMonthMapper;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tiger.project.service.IAssetMonthService;

import java.lang.reflect.Array;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Author: 64601
 * @Description: ${description}
 * @Date: 2023/2/15 14:04
 */
@Service
public class AssetMonthServiceImpl implements IAssetMonthService {

    @Autowired
    private AssetMonthMapper assetMonthMapper;

    /**
     * 新增【资产月度趋势】
     *
     * @param assetMonths 【资产月度趋势】
     * @return 结果
     */
    public int addAssetMonth(List<AssetMonth> assetMonths) {
        return assetMonthMapper.insertAssetMonth(assetMonths);
    }

    /**
     * 查询近12个月的趋势表
     *
     * @param companyId 公司id
     * @return 【资产月度趋势】集合
     */
    public List<Map<String, Object>> getAssetMonthList(Long companyId) {
        List<Map<String, Object>> list = assetMonthMapper.selectAssetMonthList(companyId);
        return packageData(list, "mon", "tenantable", "leased", "rate");
    }

    // 封装近12个月的数据。没有的用0
    List<Map<String, Object>> packageData(List<Map<String, Object>> list, String... args) {
        if (args.length == 0) {
            return null;
        }
        List<Map<String, Object>> months = generateMonths(args);
        for (int i = 0; i < months.size(); i++) {
            Map<String, Object> item = months.get(i);
            for (Map<String, Object> m : list) {
                if (Objects.equals(item.get(args[0]), m.get(args[0]))) {
                    months.set(i, m);
                }
            }
        }
        return months;
    }

    // 生成近12个月的月份
    List<Map<String, Object>> generateMonths(String... args) {
        if (args.length == 0) {
            return null;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        List<Map<String, Object>> months = new ArrayList<>();

        YearMonth currentYearMonth = YearMonth.now();
        for (int i = 0; i < 12; i++) {
            Map<String, Object> item = new HashMap<>();
            item.put(args[0], currentYearMonth.format(formatter));
            for (int j = 1; j < args.length; j++) {
                item.put(args[j], 0);
            }
            months.add(item);
            currentYearMonth = currentYearMonth.minusMonths(1);
        }
        Collections.reverse(months);
        return months;
    }
}

